package com.shyroke.daydayzhuanshiro.shiro;

import com.shyroke.daydayzhuanapi.entity.PermissionEntity;
import com.shyroke.daydayzhuanapi.entity.RoleEntity;
import com.shyroke.daydayzhuanapi.entity.UserEntity;
import com.shyroke.daydayzhuandao.respository.UserRepository;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 类名 ： shiro的Realm
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2018/12/12 17:29
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserRepository userRepository;


    /**
     * 授权，即该用户拥有什么角色以及权限
     * 步骤：根据用户名获取角色以及权限，然后设置到验证信息类并返回。
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        String userName = principalCollection.getPrimaryPrincipal().toString();

//        获取该用户的角色
        UserEntity userEntity = userRepository.findByName(userName);
        Set<RoleEntity> roles = userEntity.getRoleList();
        Set<String> roleSets = new HashSet<>();

//        获取该用户的权限集
        List<PermissionEntity> permissions = new ArrayList<>();
        Set<String> permissoinSet = new HashSet<>();

        //将List转为Set
        if(roles !=null && roles.size()>0){
            for(RoleEntity role:roles){
                roleSets.add(role.getName());
                permissions.addAll(role.getPermissions());
            }
        }

        //将List转为Set
        if(permissions!=null && permissions.size()>0){
            for(PermissionEntity p :permissions){
                permissoinSet.add(p.getName());
            }
        }


        info.addRoles(roleSets);
        info.addStringPermissions(permissoinSet);

        return info;
    }


    /**
     * 认证，即用户账号密码是否正确
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        获取用户名和密码
        String userName = (String)token.getPrincipal();
        String passWord = new String((char[]) token.getCredentials());

//        根据用户名查找该用户
        UserEntity user = userRepository.findByName(userName);

        if(user == null){
            throw new UnknownAccountException("用户名不存在");
        }

        if(!user.getPassword().equals(passWord)){
            throw new IncorrectCredentialsException("密码错误");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getName(),user.getPassword(),getName());

        return info;
    }
}
